
using UnityEngine;

public class NPCInteraction : MonoBehaviour
{
    public float interactionRange = 3f;
    public GameObject dialogueManager; // Assign the DialogueManager object to this field in the Inspector
    private bool talking = false;
    private DialogueManager _dialogueManager;
    private GameObject player;
    public AudioSource _audioSource;
    public Talking playerTalking;


    void Start()
    {
        // Ensure the dialogue manager is initially inactive
        if (dialogueManager != null)
        {
            dialogueManager.SetActive(false);
            _dialogueManager = dialogueManager.GetComponent<DialogueManager>();
            _audioSource = GetComponent<AudioSource>();
            if (_dialogueManager.dialogueData.laughter != null)
            {
                _audioSource.clip = _dialogueManager.dialogueData.laughter;
            }
    
        }
        
        player = GameObject.FindGameObjectWithTag("Player");
        playerTalking = player.GetComponent<Talking>();
    }

    void Update()
    {

        // Check for player input or other conditions to activate the dialogue
        if (Input.GetKeyDown(KeyCode.Q) && IsPlayerInRange())
        {
            // Set the dialogue manager to active when the player is in range and presses Q
            if (dialogueManager != null && !playerTalking.talking)
            {
                playerTalking.talking = true;
                dialogueManager.SetActive(true);
                talking = true;
                if (_audioSource.clip != null) _audioSource.Play();
            }
        }
        
        if (talking && !IsPlayerInRange())
        {
            _dialogueManager.CloseDialogue();
        }


    }

    bool IsPlayerInRange()
    {
        if (player != null)
        {
            float distance = Vector3.Distance(player.transform.position, transform.position);
            return distance <= interactionRange;
        }

        return false;
    }
}